<template>
    <div class="classify" style="padding-bottom: 0px;padding-top:24%">
        <!--搜索header-->
        <div class="header_search">
            <img @click="goBack()" class="back" src="../../assets/img/back.png" alt="">
            <div class="search_ipt">
                <img src="../../assets/img/search_icon.png" alt="" @click="search()">
                <input id="search" type="search" class="mui-input-clear" placeholder="搜索商品、品类" v-model="selfKeyWord"
                       @keyup="show($event)">
            </div>
        </div>
        <div class="allSort mt mb f14" v-if="showClassItem" >
            <div class="sortMenu clearfix" style=" position: fixed; top: 7%; z-index: 222;">
                <ul class="sortMenu-ul" >
                <li class="cell" v-for="item in classList" style="min-width:8%;margin:0 8px;">
                    <a @click="getNewClass(item.id)" :class="{ed1c:item.id== class_id}">{{item.cate}}</a>
                </li>
                </ul>
            </div>
        </div>
        <ul class="check_menu horizontal-list clear" v-else>
            <li @click="checkMenu(0)" :class="{active:menuIndex == 0}">综合</li>
            <li @click="checkMenu(1)" :class="{active:menuIndex == 1}">销量</li>
            <li @click="checkMenu(2)" :class="{active:menuIndex == 2}">新品</li>
            <li @click="checkMenu(3)" :class="{active:menuIndex == 3}">价格</li>
        </ul>
        <mt-loadmore :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" @bottom-status-change="handleTopChange"
                     ref="loadmore">
            <ul class="item_classify_goods horizontal-list clear">
                <li v-for="product in products" @click="goDetail(product.detailUtl,product.productId,product.new_url);">
                    <img v-if="product.image&&product.site" :src="product.image" :alt="product.productName">
                    <img v-if="!product.image&&product.site" :src="'http:'+product.thumb" :alt="product.title">
                    <img v-if="!product.site" :src="imageDomain+product.image" :alt="product.productName">
                    <p class="title" v-if="product.site == 'taobao'"><label
                            style="color: #ed1c1c">【淘宝】</label>{{product.productName}}{{product.title}}</p>
                    <p class="title" v-else-if="product.site == 'tmall'"><label
                            style="color: #ed1c1c">【天猫】</label>{{product.productName}}{{product.title}}
                    </p>
                    <p class="title" v-else><label style="color:#ed1c1c">【自营】</label>{{product.productName}}</p>
                    <p class="price">￥{{product.price}}</p>
                </li>
            </ul>
            <div slot="bottom" class="mint-loadmore-bottom">
                <span v-show="topStatus !== 'loading'" :class="{ 'rotate': topStatus === 'drop' }">↑</span>
                <span v-show="topStatus === 'loading'">Loading...</span>
            </div>
        </mt-loadmore>
    </div>
</template>

<style>
    @import url("./classify.css");
</style>
<script>
    import Layer from '../../assets/js/MessageBox'
    import API from '../../assets/js/API'

    export default {
        data() {
            return {
                topStatus: '',
                allLoaded: false,
                imageDomain: "",
                productQuery: {
                    currentPage: 1,
                    keyword: this.$route.query.keyWord,
                    sortEnum: 1,
                    fcategory: this.$route.query.fcategory,
                    tcatrgory: this.$route.query.category_id,
                    shopId: this.$route.query.shopId
                },
                allProducts:[],
                tcategoryName: this.$route.query.tcategory_name,
                products: [],
                menuIndex: 0,
                outSidePage: 1,
                outSideSort: "",
                loading: false,
                selfKeyWord: this.$route.query.keyWord,
                class_id:this.$route.query.class_id,
                apiName: this.$route.query.taoqinggouName,
                rowscount:0,//总条数
                pagesize:1,//总的页数
                showClassItem:false,
               classList: [],
               pages:1,
            }
        },
        created() {
            if(this.apiName){
                if(this.class_id>0){
                      this.getGoods()
                }else{
                   this.showClassItem=true;
                   this.getClass();
                }
               
            }else{
                  let url = API.serviceDomain + API.productArray;
                this.productQuery.sortEnum = "0";
                this.$http.post(url, this.productQuery).then(
                    (res) => {
                        if (res.body.status == '000000') {
                            if (res.body.data != null) {
                                this.products = res.body.data;
                                console.log(this.products)
                                console.log('wewerwe'+this.products[0].image)
                            } else {
                                this.outSideSearch();
                            }
                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                     )
            }
           
        },
        mounted() {
            this.imageDomain = API.imageDomain;
        },
        methods: {
            getGoods(){
                
                let url=API.taotejia+this.apiName;
                this.productQuery.sortEnum = "0";
                let form=new FormData()
                if(this.apiName=='/goods'||this.apiName=='/video'||this.apiName=='/brand'||this.apiName=='/today'){
                    form.append('cate',this.class_id)
                     form.append('page',this.productQuery.currentPage)
                }
                  this.$http.post(url,form,
                  {
                       headers: {'Content-Type': 'application/x-www-form-urlencoded,multipart/form-data'}
                  }
                  ).then(
                (res) => {
                    console.log(res.body.data)
                    if (res.body.code==1) {
                         window.scrollTo(0,0);
                        if(this.apiName=='/video'||this.apiName=='/brand'||this.apiName=='/today'){
                            if(this.productQuery.currentPage==1){
							 this.products=res.body.data.result; 
                            }else{
                                this.products = this.products.concat(res.body.data.result);
                            }
                        }else{
                            this.allProducts= res.body.data.result;
                            this.products=this.allProducts.slice((this.pages-1)*30,this.pages*30)
                            this.rowscount= res.body.data.rowscount;
                            if(res.body.data.pagecount){
                                  this.pagesize=res.body.data.pagecount
                             }
                        }  
                    }else {
                        this.allLoaded=true;
                    }
                    
                },
                (error) => {
                    Layer.showMsg("服务器开小差了...")
                    return
                }
            )

            },
            getNewClass(id){
                this.class_id=id;
                this.productQuery.currentPage=1;
                this.getGoods();
                this.allLoaded=false;
            },
             getClass(){
               let url=API.taotejia+API.cates;
               console.log(url)
                 this.$http.post(url,{},{
                      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                 }).then(
                     (res)=>{
                          console.log(res.body.data.result)
                         if(res.body.code==1){
                              this.classList=res.body.data.result
                               console.log(this.classList)
                                 this.class_id=this.classList[0].id
                                 this.getGoods()
                         }else{
                              Layer.showMsg('获取列表失败！');
                         }
                        
                     },
                     (err)=>{
                          Layer.showMsg("服务器开小差了...")
                         return
                     }
                 )
            },
            goBack() {
                this.$router.goBack()
            },
            checkMenu(index) {
                this.menuIndex = index;
                if (index == 1) {
                    this.products = [];
                    this.outSideSort = "sale";
                } else if (index == 3) {
                    this.products = [];
                    this.outSideSort = "price";
                } else {
                    this.products = [];
                }
                this.switch(index + '');
                this.productQuery.currentPage = 1;
            },
            switch(sortEnum) {
                this.productQuery.sortEnum = sortEnum;
                let url = API.serviceDomain + API.productArray;
                this.resetIndex();
                this.$http.post(url, this.productQuery).then(
                    (res) => {
                        if (res.body.status == '000000') {
                            if (res.body.data == null) {
                                this.outSideSearch();
                            } else {
                                this.products = res.body.data;
                                console.log(this.products)
                            }
                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                )
            },
            addRecord(sortEnum) {
                if(this.apiName){
                    if(!(this.apiName=='/video'||this.apiName=='/brand'||this.apiName=='/today')){
                        this.pages++;
                         console.log(-2)
                        let number=Math.ceil(this.rowscount/this.pagesize/30)
                        console.log(number)
                        if(this.pages<=number){
                            this.products = this.products.concat(this.allProducts.slice((this.pages-1)*30,this.pages*30))
                        }else{
                            if(this.apiName=='/goods'){
                                this.pages=1;
                                this.nextIndex();
                                this.getGoods()
                            }else{
                                  this.allLoaded=true;
                            }
                            
                        }
                    }else{
                         this.nextIndex();
                         this.getGoods()
                    }
                }else{
                      this.productQuery.sortEnum = sortEnum;
                    let url = API.serviceDomain + API.productArray;
                      this.nextIndex();
                    console.log(this.productQuery)
                    this.$http.post(url, this.productQuery).then(
                        (res) => {
                            console.log(res.body)
                            if (res.body.status == '000000') {
                                if (res.body.data == null) {
                                    this.outSidePage++;
                                    this.outSideSearch();
                                } else {
                                    this.products = this.products.concat(res.body.data);
                                }
                            } else {
                                Layer.showMsg(res.body.message);
                            }
                        },
                        (error) => {
                            Layer.showMsg("服务器开小差了...")
                            return
                        }
                    )
                }
              
            },
            loadTop() {
                // 加载更多数据
                this.switch(this.menuIndex + '');
                this.resetIndex();
                this.$refs.loadmore.onTopLoaded();
            },
            loadBottom() {
                // 加载更多数据
                this.addRecord(this.menuIndex + '');
                this.$refs.loadmore.onBottomLoaded();
            },
            handleTopChange(status) {
                this.topStatus = status;
            },
            nextIndex() {
                this.productQuery.currentPage = this.productQuery.currentPage + 1;
            },
            resetIndex() {
                this.productQuery.currentPage = 1;
            },
            search() {
                let keyword = "";
                if (this.selfKeyWord) {
                    keyword = this.selfKeyWord;
                } else {
                    keyword = this.tcategoryName;
                }
                if (this.selfKeyWord) {
                    this.productQuery.keyword = keyword;
                } else {
                    this.productQuery.keyword = "";
                }
                this.productQuery.currentPage = 1;
                this.productQuery.sortEnum = 1;
                this.productQuery.fcategory = "";
                this.productQuery.tcatrgory = "";
                let url = API.serviceDomain + API.productArray;
                this.$http.post(url, this.productQuery).then(
                    (res) => {
                        if (res.body.status == '000000') {
                            if (res.body.data == null) {
                                this.products = [];
                                this.outSideSearch();
                            } else {
                                this.products = res.body.data;
                            }
                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                )

            },
            outSideSearch() {
                let keyword = "";
                if (this.selfKeyWord) {
                    keyword = this.selfKeyWord;
                } else {
                    keyword = this.tcategoryName;
                }
                this.$http.post(
                    API.outsideServiceDomain + API.outsideProductSearch,
                    "key=" + keyword + "&page=" + this.outSidePage + "&sort=" + this.outSideSort,
                    {
                        headers: {
                            'Content-Type':
                                'application/x-www-form-urlencoded'
                        }
                    }
                ).then(
                    (res) => {
                        if (res.body.code = 1) {
                            let outSideProducts = res.body.data.goods;
                            if (outSideProducts != null) {
                                for (var i = 0; i < outSideProducts.length; i++) {
                                    let outSideProduct = {};
                                    outSideProduct.image = "http://" + outSideProducts[i].thumb;
                                    outSideProduct.productName = outSideProducts[i].title;
                                    outSideProduct.price = outSideProducts[i].price;
                                    outSideProduct.site = outSideProducts[i].site;
                                    outSideProduct.detailUtl = outSideProducts[i].new_url;
                                    this.products.push(outSideProduct);
                                     console.log(this.products)
                                console.log('wewerwe'+this.products[0].image)
                                }
                            } else {
                                this.allLoaded = true;// 若数据已全部获取完毕
                            }
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                )
            },
            goDetail(url, productId,new_url) {
                if (url) {
                    var w=plus.webview.create( url,'taobao');
                      w.show();//在内置浏览器打开网页
                    // plus.runtime.openURL(url,function(){
                    //      plus.runtime.openURL(url);
                    // },'com.taobao.taobao');
                }else if(new_url){
                    var w=plus.webview.create( new_url,'taobao');
                      w.show();//在内置浏览器打开网页
                    // plus.runtime.openURL(new_url,function(){
                    //      plus.runtime.openURL(new_url);
                    // },'com.taobao.taobao');
                }
                 else {
                    this.$router.push({path: '/detail', query: {productId: productId}});
                }

            },
            show(ev) {
                if (ev.keyCode == 13) {
                    this.search();
                }
            }
        }
    }
</script>
